{% extends "base.html" %}

{% block title %}重置密码 - 个人工具网站集{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
        <div class="text-center">
            <div class="mx-auto h-20 w-20 bg-blue-100 rounded-full flex items-center justify-center mb-6">
                <i class="fas fa-key text-blue-600 text-3xl"></i>
            </div>
            <h2 class="text-3xl font-bold text-gray-900 mb-2">重置密码</h2>
            <p class="text-gray-600 mb-8">为您的账户设置新密码</p>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-8">
            <!-- Flash消息 -->
            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    <div class="mb-6">
                        {% for category, message in messages %}
                            <div class="p-4 rounded-lg mb-3 {% if category == 'error' %}bg-red-50 border border-red-200{% elif category == 'success' %}bg-green-50 border border-green-200{% else %}bg-blue-50 border border-blue-200{% endif %}">
                                {% if category == 'error' %}
                                    <div class="flex items-center">
                                        <i class="fas fa-exclamation-circle text-red-500 mr-3"></i>
                                        <span class="text-red-700">{{ message }}</span>
                                    </div>
                                {% elif category == 'success' %}
                                    <div class="flex items-center">
                                        <i class="fas fa-check-circle text-green-500 mr-3"></i>
                                        <span class="text-green-700">{{ message }}</span>
                                    </div>
                                {% else %}
                                    <div class="flex items-center">
                                        <i class="fas fa-info-circle text-blue-500 mr-3"></i>
                                        <span class="text-blue-700">{{ message }}</span>
                                    </div>
                                {% endif %}
                            </div>
                        {% endfor %}
                    </div>
                {% endif %}
            {% endwith %}
            
            <!-- 账户信息 -->
            <div class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <div class="flex items-center">
                    <i class="fas fa-user text-blue-600 mr-3"></i>
                    <div>
                        <p class="text-sm text-blue-800 font-medium">重置账户密码</p>
                        <p class="text-sm text-blue-600">{{ email }}</p>
                    </div>
                </div>
            </div>
            
            <!-- 重置密码表单 -->
            <form method="POST" id="resetPasswordForm" class="space-y-6">
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-2"></i>新密码
                    </label>
                    <div class="relative">
                        <input type="password" id="password" name="password" required 
                               class="w-full px-4 py-3 pr-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                               placeholder="请输入新密码（至少6位）"
                               minlength="6">
                        <button type="button" onclick="togglePassword('password')" 
                                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600">
                            <i class="fas fa-eye" id="password-eye"></i>
                        </button>
                    </div>
                    <div class="mt-2 text-sm text-gray-500">
                        <i class="fas fa-info-circle mr-1"></i>密码长度至少6位，建议包含字母和数字
                    </div>
                </div>
                
                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-2"></i>确认新密码
                    </label>
                    <div class="relative">
                        <input type="password" id="confirm_password" name="confirm_password" required 
                               class="w-full px-4 py-3 pr-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                               placeholder="请再次输入新密码"
                               minlength="6">
                        <button type="button" onclick="togglePassword('confirm_password')" 
                                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600">
                            <i class="fas fa-eye" id="confirm_password-eye"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 密码强度指示器 -->
                <div id="passwordStrength" class="hidden">
                    <div class="text-sm font-medium text-gray-700 mb-2">密码强度：</div>
                    <div class="flex space-x-1 mb-2">
                        <div id="strength1" class="h-2 w-1/4 bg-gray-200 rounded"></div>
                        <div id="strength2" class="h-2 w-1/4 bg-gray-200 rounded"></div>
                        <div id="strength3" class="h-2 w-1/4 bg-gray-200 rounded"></div>
                        <div id="strength4" class="h-2 w-1/4 bg-gray-200 rounded"></div>
                    </div>
                    <div id="strengthText" class="text-sm text-gray-600"></div>
                </div>
                
                <div>
                    <button type="submit" id="submitBtn"
                            class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors font-medium">
                        <span id="submitText">
                            <i class="fas fa-save mr-2"></i>重置密码
                        </span>
                        <span id="submitLoading" class="hidden">
                            <i class="fas fa-spinner fa-spin mr-2"></i>处理中...
                        </span>
                    </button>
                </div>
            </form>
            
            <!-- 返回登录 -->
            <div class="mt-6 text-center">
                <a href="{{ url_for('login') }}" class="text-blue-600 hover:text-blue-500 font-medium">
                    <i class="fas fa-arrow-left mr-2"></i>返回登录
                </a>
            </div>
        </div>
        
        <!-- 安全提示 -->
        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-shield-alt text-yellow-600"></i>
                </div>
                <div class="ml-3">
                    <h4 class="text-sm font-medium text-yellow-800">安全提示</h4>
                    <div class="mt-1 text-sm text-yellow-700">
                        <ul class="list-disc list-inside space-y-1">
                            <li>请设置一个强密码以保护您的账户</li>
                            <li>不要与他人分享您的密码</li>
                            <li>建议定期更换密码</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 切换密码可见性
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const eye = document.getElementById(inputId + '-eye');
    
    if (input.type === 'password') {
        input.type = 'text';
        eye.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        eye.className = 'fas fa-eye';
    }
}

// 密码强度检查
function checkPasswordStrength(password) {
    const strengthDiv = document.getElementById('passwordStrength');
    const strengthText = document.getElementById('strengthText');
    const strengthBars = [1, 2, 3, 4].map(i => document.getElementById('strength' + i));
    
    if (password.length === 0) {
        strengthDiv.classList.add('hidden');
        return;
    }
    
    strengthDiv.classList.remove('hidden');
    
    let strength = 0;
    let feedback = [];
    
    // 长度检查
    if (password.length >= 8) {
        strength++;
    } else {
        feedback.push('至少8个字符');
    }
    
    // 包含小写字母
    if (/[a-z]/.test(password)) {
        strength++;
    } else {
        feedback.push('包含小写字母');
    }
    
    // 包含大写字母
    if (/[A-Z]/.test(password)) {
        strength++;
    } else {
        feedback.push('包含大写字母');
    }
    
    // 包含数字
    if (/\d/.test(password)) {
        strength++;
    } else {
        feedback.push('包含数字');
    }
    
    // 更新强度条
    strengthBars.forEach((bar, index) => {
        if (index < strength) {
            if (strength <= 1) {
                bar.className = 'h-2 w-1/4 bg-red-500 rounded';
            } else if (strength <= 2) {
                bar.className = 'h-2 w-1/4 bg-yellow-500 rounded';
            } else if (strength <= 3) {
                bar.className = 'h-2 w-1/4 bg-blue-500 rounded';
            } else {
                bar.className = 'h-2 w-1/4 bg-green-500 rounded';
            }
        } else {
            bar.className = 'h-2 w-1/4 bg-gray-200 rounded';
        }
    });
    
    // 更新文本提示
    if (strength <= 1) {
        strengthText.textContent = '弱密码';
        strengthText.className = 'text-sm text-red-600';
    } else if (strength <= 2) {
        strengthText.textContent = '中等密码';
        strengthText.className = 'text-sm text-yellow-600';
    } else if (strength <= 3) {
        strengthText.textContent = '强密码';
        strengthText.className = 'text-sm text-blue-600';
    } else {
        strengthText.textContent = '很强的密码';
        strengthText.className = 'text-sm text-green-600';
    }
    
    if (feedback.length > 0) {
        strengthText.textContent += ' (建议: ' + feedback.join(', ') + ')';
    }
}

// 密码确认检查
function checkPasswordMatch() {
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    const confirmInput = document.getElementById('confirm_password');
    
    if (confirmPassword.length > 0) {
        if (password === confirmPassword) {
            confirmInput.classList.remove('border-red-300');
            confirmInput.classList.add('border-green-300');
        } else {
            confirmInput.classList.remove('border-green-300');
            confirmInput.classList.add('border-red-300');
        }
    } else {
        confirmInput.classList.remove('border-red-300', 'border-green-300');
    }
}

// 表单提交
document.getElementById('resetPasswordForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    const submitLoading = document.getElementById('submitLoading');
    
    // 基本验证
    if (!password || !confirmPassword) {
        showErrorMessage('请填写所有字段');
        return;
    }
    
    if (password !== confirmPassword) {
        showErrorMessage('两次输入的密码不一致');
        return;
    }
    
    if (password.length < 6) {
        showErrorMessage('密码长度至少6位');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitText.classList.add('hidden');
    submitLoading.classList.remove('hidden');
    
    // 发送请求
    fetch(window.location.href, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            password: password,
            confirm_password: confirmPassword
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccessMessage(data.message);
            setTimeout(() => {
                window.location.href = data.redirect_url || '{{ url_for("login") }}';
            }, 2000);
        } else {
            showErrorMessage(data.message || '重置失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitText.classList.remove('hidden');
        submitLoading.classList.add('hidden');
    });
});

// 事件监听
document.getElementById('password').addEventListener('input', function() {
    checkPasswordStrength(this.value);
    checkPasswordMatch();
});

document.getElementById('confirm_password').addEventListener('input', checkPasswordMatch);

// 消息显示函数
function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 回车键提交
document.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('resetPasswordForm').dispatchEvent(new Event('submit'));
    }
});
</script>
{% endblock %}